using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Xml;

namespace TmxLib
{
    public class ExcludeContextCollection : Collection<string>
    {
        public void ToXml(XmlWriter writer)
        {
            writer.WriteStartElement("ExcludeList");
            foreach(string s in this)
                writer.WriteElementString("context", s);

            writer.WriteEndElement();
        }

        public static ExcludeContextCollection Parse(XmlElement parent)
        {
            ExcludeContextCollection ret = new ExcludeContextCollection();
            XmlNodeList nl = parent.SelectNodes(".//ExcludeList/context");
            foreach(XmlElement el in nl)
            {
                string context = el.InnerText;
                if (context != null && context.Length > 0)
                    ret.Add(context);
            }

            return ret;
        }
    }

    public class ExcludeContextCollectionSnapshot
    {
        private ExcludeContextCollection _excludeList;
        Dictionary<string, object> _keys = new Dictionary<string, object>();

        public ExcludeContextCollectionSnapshot(ExcludeContextCollection excludeList)
        {
            _excludeList = excludeList;

            foreach (string s in excludeList)
                _keys[s] = null;
        }

        public bool IsExcluded(string context)
        {
            string[] arr = context.Split(':');
            for(int l=0; l<arr.Length; l++)
            {
                string path = string.Join(":", arr, 0, l + 1);
                if (_keys.ContainsKey(path))
                    return true;
            }

            return false;
        }

        public static readonly ExcludeContextCollectionSnapshot Empty = 
            new ExcludeContextCollectionSnapshot(new ExcludeContextCollection());
    }
}
